package com.rmi;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

class RmiStream {

    public String toReadString(InputStream stream) {
        try {
            byte[] lengthBuffer = new byte[4];
            stream.read(lengthBuffer);
            System.out.println("toReadString");
            int length = intFromByteArray(lengthBuffer);
            System.out.println("  length=" + length);
            byte[] bytes = new byte[length];
            int readed = stream.read(bytes);
            if (readed != bytes.length) {
                throw new RuntimeException("readed " + readed + " but should be " + bytes.length);
            }
            String value = new String(bytes, "UTF8");
            System.out.println("  String:" + value);
            return value;
        } catch (IOException ex) {
            throw new RuntimeException(ex);
        }
    }

    byte[] toByteArray(int value) {
        return new byte[]{
            (byte) (value >> 24),
            (byte) (value >> 16),
            (byte) (value >> 8),
            (byte) value};
    }

    int intFromByteArray(byte[] array) {
        return array[0] << 24
                | (array[1] & 0xFF) << 16
                | (array[2] & 0xFF) << 8
                | (array[3] & 0xFF);
    }

    public static String bytesToHexString(byte[] bytes) {
        StringBuilder sb = new StringBuilder();
        boolean first = true;
        for (byte b : bytes) {
            if (!first) {
                sb.append(" ");
            }
            sb.append(String.format("%02x", b & 0xff));
            first = false;
        }
        return sb.toString();
    }

    public void writeString(OutputStream outputStream, String string) {
        try {
            System.out.println("writeString");
            System.out.println("  String:" + string);
            System.out.println("  length:" + string.length());
            byte[] bytes = string.getBytes("UTF8");
            System.out.println("  blength:" + bytes.length);

            byte[] bytesLength = toByteArray(bytes.length);
            intFromByteArray(bytesLength);

            outputStream.write(bytesLength);
            outputStream.write(bytes);
            outputStream.flush();
        } catch (IOException ex) {
            throw new RuntimeException(ex);
        }
    }
}
